#include <stdio.h>
#include<stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define TASK_NUM 5
typedef void (*task_t)();
void download()
{
printf("this is a download task running\n ");
}

void printlog()
{
printf("this is a printlog task running\n");
}

void showinfo()
{
printf("this is a showinfo task running\n");
}
int addtasks(task_t tasks[],task_t t)
{
for(int i=0;i<TASK_NUM;i++)
{
if(tasks[i]==NULL)
{
tasks[i]=t;
return 1;
}
}
return 0;
}
void initwork(task_t tasks[],int num)
{
for(int i=0;i<num;i++)
{
tasks[i]=NULL;
}
}

void executework(task_t tasks[],int num)
{
for(int i=0;i<num;i++)
{
if(tasks[i]) tasks[i]();
}
}
void worker(int cnt)
{
printf("I am a child,pid:%d,cnt:%d\n",getpid(),cnt);
}
int main()
{
task_t tasks[TASK_NUM];
initwork(tasks,TASK_NUM);
addtasks(tasks,download);
addtasks(tasks,printlog);
addtasks(tasks,showinfo);
pid_t id=fork();
if(id==0)
{
int cnt=10;
while(cnt)
{
worker(cnt);
cnt--;
sleep(1);
}
exit(0);
}
while(1)
{
int status=0;
pid_t rid=waitpid(id,&status,WNOHANG);
if(rid>0)
{
printf("quit success exit code:%d,exit signal:%d\n",((status>>8)&0xFF),(status&0x7F));
break;
}
else if(rid==0)
{
printf("child is alive,wait again\n");
executework(tasks,TASK_NUM);
}
else
{
printf("wait fail\n");
break;
}
sleep(1);
}
return 0;
}
